<?php
  // class.esmsservice.php --- Time-stamp: <2008-10-08 12:03:14 root>
  // Copyright 2008 Julian Qian
  // Author: tsien@IBM-L3KWG75
  // Version: $Id: lib.php,v 0.0 2008/06/09 03:33:56 tsien Exp $
  // Keywords: 

require_once('nusoap/nusoap.php');

// $e = new ESmsService("BJYTXY","123456","EsmsService_act.wsdl","041184040464","106561100464");
// $e->init();
// $e->putMsg(array("1348858858"=>"testmsg"), 60);
// $info = $e->getMsg();
// $e->clear();

class ESmsService extends nusoap_client {
	var $username;
	var $password;
	var $wsdl;
	var $phonecode;
	var $servecode;
	var $msglen = 110; // length of msg string
	
	var $debug = 0; // 0: none 1: log 2: verbose	
	
	var $login_status = array(
		0=>"Login successfully!",
		1=>"Connect to system database failed!",
		2=>"Your login password cannot be empty!",
		3=>"This account does not exist!",
		4=>"Web service is closed now, can not communicate it.",
		5=>"Your password is uncorrect.",
		6=>"Your message quantity is limited.",
		7=>"Exceptional, maybe your account has logined.",
		10=>"You cannot login from two clients at one time.",
		);
	var $sendMessageQueue_status = array(
		0=>"Send message to queue successfully!",
		3=>"Your session has been time out, please login again.",
		4=>"Web service is closed now, can not communicate it.",
		6=>"Message Queue has not been opened.",
		7=>"Your message quantity is limited, please re-pay for it.",
		8=>"Message quantity to be sent this time overloads.",
		11=>"Your message sending speed is faster than system's.",
		12=>"Client did not send message every one minute. It is possible that more than one client are opened and system will deny them.",
		);
	
	function ESmsService($username,$password,$wsdl,$phonecode,$servecode){
		parent::nusoap_client($wsdl, "wsdl");
		$err = $this->getError();
		if($err){
			$this->logging($err);
			return null;
		}
		// set default encoding.
		$this->soap_defencoding = 'UTF-8';
		$this->decode_utf8 = false;
		$this->xml_encoding = 'UTF-8';

		// set debug level
		$this->debugLevel = $this->debug;
		
		$this->username = $username;
		$this->password = $password;
		$this->phonecode = $phonecode;
		$this->servecode = $servecode;

		$this->logging("ESmsService class construct begins...");
		foreach(compact("username","password","wsdl","phonecode","servecode") as $a=>$b){
			$this->logging("$a => $b");
		}
	}

	function init(){
		$this->logging("Web service client init to login...");
		if(7 == ($ret = $this->Login())){
			$this->logging("Some active users logined, clear them.");

			$this->ClearActiveUser();
			$ret = $this->Login();
		}

		if(2 == $this->debug){
			$this->logging("\n################Login\n".$this->request.
						   "\n################\n".$this->response.
						   "\n################\n");
		}
		
		if(0 != $ret){
			$this->logging( $login_status[$ret]);
			return -1;
		}
		$this->logging("ESmsService logined successfully!");
		return 0;
	}

	function clear(){
		$this->ClearActiveUser();
	}

	// $msginfo = array("13800138000"=>"msg", ...)
	function putMsg(&$msginfo, $time_offset=10){
		if(is_array($msginfo) && count($msginfo)){
			$this->logging("begin to putMsg in $time_offset secs...");
			
			$dstart = $this->_getDStart( $this->getCurrentDate() , $time_offset);
			$count = count($msginfo);
			$ret = $this->insertTaskTable(current($msginfo), $dstart, $count);
			if(true == $ret){
				$ret = $this->sendMessageQueue($msginfo);
				if(0 == $ret) {
					$this->logging("putMsg successfully!");
					return 0;
				}
				else $this->logging( $this->sendMessageQueue_status[$ret]);
			}
		}
		$this->logging( "putMsg failed!");
		return -1;
	}

	// return (string) 13800138000:msg0,13800138001:msg1,...
	function getMsg(){
		$this->logging( "begin to getMsg...");
		$ret = $this->getMOInfo();
		if(count($ret)){
			return implode(",",$ret);
		}else{
			return "";
		}
	}

	function Login(){
		$param = array("userName" => $this->username,
					   "password" => $this->password);
		$result = $this->call("Login", array("parameters" => $param ));
		return $result["LoginResult"];
	}

	function ClearActiveUser(){
		$this->logging("ClearActiveUser()");
		$this->call("ClearActiveUser", array("parameters"=> array("code" => $this->servecode)));
	}

	function getCurrentDate(){
		$result = $this->call("getCurrentDate");
		return $result["getCurrentDateResult"];
	}

	function insertTaskTable($content,$dstart,$count){
		$fargs = func_get_args();
		$this->logging( "insertTaskTable()");
		
		$param = array("CompanyCode"=>$this->servecode,
					   "TaskCode"=>$this->_getTaskCode(),
					   "Content"=>$content,
					   "dStart"=>$dstart, // "dStart"=>"2008-06-08 16:25:00",
					   "i_allCount"=>$count);
		
		$this->logging(var_export($param, TRUE));
		
		$result = $this->call("insertTaskTable", array("parameters" => $param));

		if(2 == $this->debug){
			$this->logging("\n################insertTaskTable\n".$this->request.
						   "\n################\n".$this->response.
						   "\n################\n");
		}
		
		return $result["insertTaskTableResult"];
	}

	function sendMessageQueue(&$msginfo){
		$this->logging("sendMessageQueue()");
		$phone_str = array();
		$msg_str = array();
		foreach ( $msginfo as $phone => $msg ) {
		    $phone_str[] = "<anyType xsi:type=\"xsd:string\">$phone</anyType>";
			if(strlen($msg) < $this->msglen){
				$msgstr = $msg;
			}else{
				$msgstr = substr($msg,0,$this->msglen);
			}
			$msg_str[]   = "<anyType xsi:type=\"xsd:string\">$msgstr</anyType>";

		}
		
		$param = "<sendMessageQueue xmlns=\"http://tempuri.org/\"><CompanyCode>".
			$this->servecode."</CompanyCode><PhoneCollection>".
			(implode("",$phone_str))."</PhoneCollection><Content>".
			(implode("",$msg_str))."</Content><PhoneCode>".
			$this->phonecode."</PhoneCode></sendMessageQueue>";

		$this->logging($param);
		
		$result = $this->call("sendMessageQueue", $param);

		if(2 == $this->debug){
			$this->logging("\n################sendMessageQueue\n".$this->request.
						   "\n################\n".$this->response.
						   "\n################\n");
		}
		
		return $result["sendMessageQueueResult"];
	}

	// sample:
    // array(1) {
    //   ["getMOInfoResult"]=>
    //   array(1) {
    //     ["anyType"]=>
    //     string(46) "13488668678,106561100464,2008-6-10 23:52:34,test"
    //   }
    // }
	// return array("13800138000:test1",...)
	function &getMOInfo(){
		$result = $this->call("getMOInfo", array("parameters" => array("CompanyCode"=>$this->servecode)));

		if(2 == $this->debug){
			$this->logging("\n################insertTaskTable\n".$this->request.
						   "\n################\n".$this->response.
						   "\n################\n");
		}
		$this->logging(var_export($result), TRUE);

		// OUTPUT sample:
		// array (
		// 	  'getMOInfoResult' =>
		// 	  array (
		// 		      'anyType' =>
		// 		      array (
		// 				  0 => '13488668678,106561100464,2008-10-8 0:53:56,bf',
		// 				  1 => '13488668678,106561100464,2008-10-8 0:57:29,cf',
		// 				  2 => '13488668678,106561100464,2008-10-8 10:41:24,bf',
		// 				  ),
		// 		  ),
		// 	)
		// OR
		// 	array (
		// 		  'getMOInfoResult' =>
		// 		  array (
		// 			  'anyType' => '13488668678,106561100464,2008-10-8 11:56:33,zf',
		// 			  ),
		// 		)
		$ret = array();
		if(is_array($result) &&
		   is_array($result["getMOInfoResult"])){
			$res = $result["getMOInfoResult"]["anyType"];
			if(is_array($res)){
				foreach($res as $b){
					$ms = explode(",", $b);
					$ret[] = $ms[0].":".$ms[3];
				}
			}else{
				$ms = explode(",", $res);
				$ret[] = $ms[0].":".$ms[3];				
			}
		}
		return $ret;
	}

	// return bool
	function GetStatus(){
		$result = $this->call("GetStatus");
		return $result["GetStatusResult"];
	}

	function logging($log){
		if($this->debug){
			echo "$log\n";
		}
	}

	function _getTaskCode(){
		list($sec, $microsec) = explode(" ", microtime());
		$time = $sec.(substr(strval($microsec),2,3));
		$millisec = substr($time, -9);
		return intval($millisec);
	}

	function _getDStart($ft, $time_offset=3){
		$atime = strtotime($ft);
		// increment 10 sec
		return date("Y-m-d H:i:s", $atime + $time_offset);
	}
}


?>
